//
//  TBRTextMapController.m
//  TBRentClient
//
//  Created by tonbright on 2018/4/23.
//  Copyright © 2018年 tonbright. All rights reserved.
//
#import "TBRTextMapController.h"
#import "TBRTextMapModel.h"
@interface TBRTextMapController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
//地图图层
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic,strong)BMKSuggestionSearch *suggestionSearch;
@property (nonatomic,strong)BMKPoiSearch *poiSearch;
@property (nonatomic , strong)NSMutableArray *dataArr;

@property (nonatomic,copy)NSString *searchStr;

@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

//地图定位服务
@property (nonatomic, strong) BMKLocationService *locationService;

@property (nonatomic,copy)NSString *locationCity;//定位城市
@property (nonatomic,copy)NSString *locationProvince;//定位省份
@property (nonatomic,copy)NSString *locationArea;//定位区域
@property (nonatomic,copy)NSString *currentCity;//当前选择城市  默认选择上海

@property (nonatomic,strong)UITableView *tableView;

/***
 <存储地图定位自己和目标位置坐标>
 ***/
@property (nonatomic)CLLocationCoordinate2D beginingCoordinate;

@property (nonatomic)CLLocationCoordinate2D destinationCoordinate;

/***
 <存储定位地图的位置名称>
 ***/
@property (nonatomic , strong)NSString *myNameStr;
@property (nonatomic , strong)NSString *toNameStr;

@property (nonatomic,strong)NSMutableArray *suggestSearchArray;
@property (nonatomic,strong)BMKSuggestionSearchOption *option;//搜索建议
@end

@implementation TBRTextMapController

- (void)viewDidLoad {
    [super viewDidLoad];
    _searchStr = @"";
//    [self.searchBar setBackgroundImage:[UIImage new]];
    self.searchBar.delegate = self;
    [self.searchBar setBackgroundImage:[UIImage new]];
    [self.searchBar setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1]];
    self.searchBar.barTintColor = [UIColor redColor];

    [self startLocation];
    
    [self setSuggestionSearch];
//    [self lujingguihua];
    
    [self setupTableView];
    _suggestSearchArray = [NSMutableArray array];
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchBar.bottom).offset(0);
        make.bottom.equalTo(self.sureBtn.top).offset(0);
        make.leading.trailing.offset(0);
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"TBRHomeScrollCell" bundle:nil] forCellReuseIdentifier:@"TBRHomeScrollCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TBRModuleCell" bundle:nil] forCellReuseIdentifier:@"TBRModuleCellId"];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.hidden = YES;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellId"];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}

#pragma mark - 实现数据源方法
#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.suggestSearchArray.count;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellId" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    TBRTextMapModel *model = self.suggestSearchArray[indexPath.row];
    cell.textLabel.text = model.titleName;
    //设置数据
    //返回
    return cell;
}


- (void)setSuggestionSearch {
    _suggestionSearch = [[BMKSuggestionSearch alloc]init];
    _suggestionSearch.delegate = self;
    self.option = [[BMKSuggestionSearchOption alloc]init];
}
//实现Delegate处理回调结果
-(void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:(BMKSuggestionResult*)result errorCode:(BMKSearchErrorCode)error{
    self.suggestSearchArray = [NSMutableArray array];

    if(error==BMK_SEARCH_NO_ERROR){
        //在此处理正常结果
        NSArray *searchList = result.keyList;//搜索结果数组
        NSArray *ptList = result.ptList;//经纬度数组
        NSArray *districtList = result.districtList;//区域数组
        [ptList enumerateObjectsUsingBlock:^(NSValue *value, NSUInteger idx, BOOL * _Nonnull stop) {
            TBRTextMapModel *textModel = [TBRTextMapModel new];
            CLLocationCoordinate2D coor;
            [value getValue:&coor];
            textModel.titleName = searchList[idx];
            textModel.coord = coor;
            [self.suggestSearchArray addObject:textModel];
        }];
        self.tableView.hidden = NO;
        [self.tableView reloadData];
    }else{
        NSLog(@"抱歉，未找到结果");
    }
}



- (void)lujingguihua {
    //初始化检索对象
    BMKRouteSearch *routeSearch = [[BMKRouteSearch alloc] init];
    //设置delegate，用于接收检索结果
    routeSearch.delegate = self;
    //构造驾车查询基础信息类
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    start.name = @"龙华中路地铁站";
    start.cityName = @"上海";//31.1840470000,121.4571060000
    start.pt = CLLocationCoordinate2DMake(31.1840470000, 121.4571060000);
    
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    end.name = @"泗泾";
    end.cityName = @"上海";//31.1116200000,121.2700500000
    end.pt = CLLocationCoordinate2DMake(31.1116200000, 121.2700500000);
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = start;
    drivingRouteSearchOption.to = end;
    drivingRouteSearchOption.drivingRequestTrafficType = BMK_DRIVING_REQUEST_TRAFFICE_TYPE_NONE;//不获取路况信息
    BOOL flag = [routeSearch drivingSearch:drivingRouteSearchOption];
    if(flag)
    {
        NSLog(@"car检索发送成功");
    }
    else
    {
        NSLog(@"car检索发送失败");
    }
}


/**
 *返回驾乘搜索结果--------------------时间距离等信息
 *@param searcher 搜索对象
 *@param result 搜索结果，类型为BMKDrivingRouteResult
 *@param error 错误号，@see BMKSearchErrorCode------------
 */
- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error {
    NSLog(@"onGetDrivingRouteResult error:%d", (int)error);
    if (error == BMK_SEARCH_NO_ERROR) {
        //成功获取结果
        for (BMKDrivingRouteLine *line in result.routes) {
            BMKTime *time = line.duration;
            //line.distance;这个是最终的路线距离额---------每条线路的
            NSLog(@"%d----%d---%d",time.dates,time.hours,time.minutes);
        }
    } else {
        //检索失败
    }
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _poiSearch.delegate = self;
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    
    [_mapView setZoomLevel:18];
}



-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _poiSearch.delegate = nil;
    _locationService.delegate = nil;
    _suggestionSearch.delegate = nil;
}


- (void)startLocation {
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    _mapView.showsUserLocation = YES;
    _mapView.showMapScaleBar = YES; // 设定是否显式比例尺
    _mapView.delegate = self;
    
    _locationService = [[BMKLocationService alloc] init];
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    [_mapView setZoomLevel:18];

}



/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    CLLocation *location = userLocation.location;
//    apMark *nowAnno = [[mapMark alloc] init];
//    nowAnno.coordinate = location.coordinate;
//    nowAnno.title = @"我的位置";
//    nowAnno.type = 0;
//    [self.mapView addAnnotation:nowAnno];
    BMKCoordinateSpan span;
    span.latitudeDelta = 0.5;
    span.longitudeDelta = 0.5;
    BMKCoordinateRegion region;
    region.center = location.coordinate;
    region.span = span;
    [self.mapView setRegion:region animated:YES];
    //停止定位
    [_locationService stopUserLocationService];
    //检索----添加检索吗?---------------
    [self addBMKCloudSearchWith:userLocation];
    [_mapView setZoomLevel:18];

    [_mapView updateLocationData:userLocation];
    CLLocationCoordinate2D coor;
    coor.latitude = userLocation.location.coordinate.latitude;
    coor.longitude = userLocation.location.coordinate.longitude;

    //反地理编码----
    //    注意：必须初始化地理编码类
    BMKGeoCodeSearch *_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
    _geoCodeSearch.delegate = self;
    BMKReverseGeoCodeOption *reverseOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseOption.reverseGeoPoint = coor;
    [_geoCodeSearch reverseGeoCode:reverseOption];
    //--------------------------------------------------
}


- (void)addBMKCloudSearchWith:(BMKUserLocation *)userLocation{
//    BMKNearbySearchOption  BMKCitySearchOption
    // 初始化云检索服务
    _poiSearch = [[BMKPoiSearch alloc] init];
    _poiSearch.delegate = self;
//    // 设置地图级别
//    [self.mapView setZoomLevel:17];
//    self.mapView.isSelectedAnnotationViewFront = YES; //设定是否总让选中的annotaion置于最前面
//    BMKNearbySearchOption * option = [[BMKNearbySearchOption alloc]init];
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
    
    citySearchOption.pageIndex = 0;
    
    citySearchOption.pageCapacity = 20;
    
    citySearchOption.city= @"上海";
    
    citySearchOption.keyword = @"龙华";
    
//    citySearchOption.
    
    
//    /***
//     <这个值本来是传过来的不是固定的，我这里写的固定是方便大家看>
//     ***/
////    option.keyword = @"成都市金牛区万达广场";
//    option.location = userLocation.location.coordinate;
//
////    self.beginingCoordinate = option.location;
//    NSLog(@"option.loction == %f  %f", self.beginingCoordinate.latitude, self.beginingCoordinate.longitude);
//    option.radius = 10000;
//
//    /***
//     <因为我需要一个定位所以我就拿一个位置的信息>
//     ***/
//    option.pageCapacity = 1;
//
    BOOL flag = [_poiSearch poiSearchNearBy:citySearchOption];
    if (flag) {
        NSLog(@"检索发送成功");
    }else{
        NSLog(@"检索发送失败");

    }
}


#pragma mark implement BMKSearchDelegate
/***
 <检索数据回调，数据都在BMKPoiResult里边，拿出来想怎么用都行>
 ***/
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error{
//    self.addressArray = [NSMutableArray array];----------
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
//        result.currPoiNum = 1;
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
//            mapMark* item = [[mapMark alloc]init];
//            item.coordinate = poi.pt;
//            self.destinationCoordinate = item.coordinate;
//            NSLog(@"%f  %f", self.destinationCoordinate.longitude ,  self.destinationCoordinate.latitude);
//
//            item.title = poi.name;
//            NSLog(@"self.title%@",item.title);
//            item.type = 1;
//            [self.dataArr addObject:poi];
//            [annotations addObject:item];
        }
        [self.mapView addAnnotations:annotations];//添加大头针
        [self.mapView showAnnotations:annotations animated:YES];//显示
    } else if (error == BMK_SEARCH_PERMISSION_UNFINISHED){
        NSLog(@"用户没有授权");
    } else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD) {
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        // result.cityList;
        NSLog(@"起始点有歧义");
    }
    else{
        NSLog(@"检索失败：%d",error);
    }
}




/***
 <点击回到自己的位置>
 ***/
-(void)backToMyselfLocatin:(UIButton *)sender{
    BMKCoordinateRegion region ;//表示范围的结构体
    //设置自己为中心点
    region.center = self.beginingCoordinate;//中心点
    region.span.latitudeDelta = 0.01;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
    region.span.longitudeDelta = 0.01;//纬度范围
    [_mapView setRegion:region animated:YES];
}


- (void)bianma {
    BMKGeoCodeSearch *searcher =[[BMKGeoCodeSearch alloc]init];
    searcher.delegate = self;
    //发起地理位置检索
    BMKGeoCodeSearchOption *geoCodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    geoCodeSearchOption.address = @"此处填写您需要检索的地址";
    geoCodeSearchOption.city = @"北京";
    BOOL flag = [searcher geoCode:geoCodeSearchOption];
    if(flag)
    {
        NSLog(@"geo检索发送成功");
    }
    else
    {
        NSLog(@"geo检索发送失败");
    }
}
//返回地址信息搜索结果
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

#pragma mark 代理方法返回反地理编码结果
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    __weak typeof(self) weakSelf = self;
    if (result) {

        //        // 定位一次成功后就关闭定位
        //        [_locService stopUserLocationService];
        
    }else{
        NSLog(@"%@", @"找不到相对应的位置");
    }
    
}



- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay {
    if ([overlay isKindOfClass:[BMKCircle class]])
    {
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [[UIColor alloc] initWithRed:123/255.0 green:211/255.0 blue:251/255.0 alpha:0.3];
        circleView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.5];
        circleView.lineWidth = 1.0;
        circleView.lineDash = YES;
        return circleView;
    }
    return nil;
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = NO;// 设置该标注点动画显示
//        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
//
//        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
//
//        newAnnotationView.animatesDrop = NO;// 设置该标注点动画显示
//
//        newAnnotationView.annotation=annotation;
//
//        newAnnotationView.image = [UIImage imageNamed:@"mapicon"];   //把大头针换成别的图片
//
//        newAnnotationView.size = CGSizeMake(20, 33);
        
    }
    return nil;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.searchBar setShowsCancelButton:NO animated:YES];
}

#pragma mark -
#pragma mark - searchBar的代理方法
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    _searchStr = searchText;
    
    self.option.cityname = @"上海";//根据选择的地址来操作-------
    self.option.keyword=searchText;
    
    if ([HelpObject isBlankString:searchText]) {
        self.suggestSearchArray = [NSMutableArray array];
        [self.tableView reloadData];
        return;
    }
    
    BOOL flag=[_suggestionSearch suggestionSearch:self.option];
    if(flag){
        NSLog(@"建议检索发送成功");
    }else{
        NSLog(@"建议检索发送失败");
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:NO animated:YES];
    self.searchBar.text = @"";
    _searchStr = @"";
    _suggestSearchArray = [NSMutableArray array];
    [self.tableView reloadData];
//    [self getData];
    [self.view endEditing:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.view endEditing:YES];
    [self.searchBar setShowsCancelButton:NO animated:YES];
//    self.option.cityname = @"上海";//根据选择的地址来操作-------
//    self.option.keyword=searchText;
//    BOOL flag=[_suggestionSearch suggestionSearch:self.option];
//    if(flag){
//        NSLog(@"建议检索发送成功");
//    }else{
//        NSLog(@"建议检索发送失败");
//    }
}

@end
